<template>
  <div class="interview-analysis-container">
    <a-card title="面试数据分析" :bordered="false">
      <a-row :gutter="[16, 16]">
        <a-col :span="8">
          <a-card title="平均笔试成绩" :bordered="false">
            <div class="score-card">
              <div class="score-value">{{ examAvgScore }}</div>
              <div class="score-label">分</div>
            </div>
          </a-card>
        </a-col>
        <a-col :span="8">
          <a-card title="平均HR面试成绩" :bordered="false">
            <div class="score-card">
              <div class="score-value">{{ hrAvgScore }}</div>
              <div class="score-label">分</div>
            </div>
          </a-card>
        </a-col>
        <a-col :span="8">
          <a-card title="平均全流程成绩" :bordered="false">
            <div class="score-card">
              <div class="score-value">{{ fullProcessAvgScore }}</div>
              <div class="score-label">分</div>
            </div>
          </a-card>
        </a-col>
      </a-row>

      <a-divider />

      <!-- 技术面试信息 -->
      <a-row :gutter="[16, 16]">
        <a-col :span="24">
          <a-card title="技术面试统计" :bordered="false">
            <a-row :gutter="[16, 16]" v-if="hasTechInterviewData">
              <a-col :span="8">
                <div class="tech-info-card">
                  <div class="tech-info-title">总面试次数</div>
                  <div class="tech-info-value">{{ techInterviewInfo?.interviewCount || 0 }}</div>
                  <div class="tech-info-label">次</div>
                </div>
              </a-col>
              <a-col :span="8">
                <div class="tech-info-card">
                  <div class="tech-info-title">平均语速</div>
                  <div class="tech-info-value">
                    {{ (techInterviewInfo?.avgSpeechRate || 0).toFixed(2) }}
                  </div>
                  <div class="tech-info-label">字/秒</div>
                </div>
              </a-col>
              <a-col :span="8">
                <div class="tech-info-card">
                  <div class="tech-info-title">平均面试时长</div>
                  <div class="tech-info-value">
                    {{ formatDuration(techInterviewInfo?.avgInterviewDuration || 0) }}
                  </div>
                  <div class="tech-info-label">分钟</div>
                </div>
              </a-col>
            </a-row>
            <a-empty v-else description="暂无技术面试数据" />
          </a-card>
        </a-col>
      </a-row>

      <a-divider />

      <!-- 简历质量统计 -->
      <a-row :gutter="[16, 16]">
        <a-col :span="24">
          <a-card title="简历质量统计" :bordered="false">
            <a-tabs default-active-key="1">
              <a-tab-pane key="1" tab="昨日简历质量">
                <div v-if="hasResumeQualityDailyData" class="table-container">
                  <a-table
                    :dataSource="resumeQualityDaily"
                    :columns="resumeColumns"
                    :pagination="{ pageSize: 5 }"
                    :rowKey="(record) => record.resumeId"
                  >
                    <template #bodyCell="{ column, record }">
                      <template v-if="column.dataIndex === 'minTotalScore'">
                        <span
                          class="score-text"
                          :style="{ color: getScoreColor(record.minTotalScore) }"
                        >
                          {{ record.minTotalScore }}
                        </span>
                      </template>
                      <template v-else-if="column.dataIndex === 'action'">
                        <a-button type="link" @click="downloadResume(record.resumeUrl)"
                          >下载简历</a-button
                        >
                      </template>
                    </template>
                  </a-table>
                </div>
                <a-empty v-else description="暂无昨日简历数据" />
              </a-tab-pane>
              <a-tab-pane key="2" tab="历史简历质量">
                <div class="date-selector">
                  <a-date-picker
                    v-model:value="selectedResumeDate"
                    :disabled-date="disabledDate"
                    @change="handleResumeQualityDateChange"
                    placeholder="选择日期"
                  />
                  <span class="selected-date-text" v-if="formattedResumeSelectedDate">
                    当前查询: {{ formattedResumeSelectedDate }}
                  </span>
                </div>
                <div v-if="hasResumeQualityHistoryData" class="table-container">
                  <a-table
                    :dataSource="resumeQualityHistory"
                    :columns="resumeColumns"
                    :pagination="{ pageSize: 5 }"
                    :rowKey="(record) => record.resumeId"
                  >
                    <template #bodyCell="{ column, record }">
                      <template v-if="column.dataIndex === 'minTotalScore'">
                        <span
                          class="score-text"
                          :style="{ color: getScoreColor(record.minTotalScore) }"
                        >
                          {{ record.minTotalScore }}
                        </span>
                      </template>
                      <template v-else-if="column.dataIndex === 'action'">
                        <a-button type="link" @click="downloadResume(record.resumeUrl)"
                          >下载简历</a-button
                        >
                      </template>
                    </template>
                  </a-table>
                </div>
                <a-empty
                  v-else
                  :description="`${formattedResumeSelectedDate || '选定日期'} 暂无数据`"
                />
              </a-tab-pane>
            </a-tabs>
          </a-card>
        </a-col>
      </a-row>

      <a-divider />

      <a-row :gutter="[16, 16]">
        <a-col :span="12">
          <a-card title="昨日面试行为统计" :bordered="false">
            <div v-if="hasDailyBehaviorData" class="chart-container">
              <v-chart class="chart" :option="dailyBehaviorOption" autoresize />
            </div>
            <a-empty v-else description="暂无昨日数据" />
          </a-card>
        </a-col>
        <a-col :span="12">
          <a-card title="面试行为趋势统计" :bordered="false">
            <div class="date-selector">
              <a-date-picker
                v-model:value="selectedDate"
                :disabled-date="disabledDate"
                @change="handleDateChange"
                placeholder="选择日期"
              />
              <span class="selected-date-text" v-if="formattedSelectedDate">
                当前查询: {{ formattedSelectedDate }}
              </span>
            </div>
            <div v-if="hasMultiBehaviorData" class="chart-container">
              <v-chart class="chart" :option="multiBehaviorOption" autoresize />
            </div>
            <a-empty v-else :description="`${formattedSelectedDate || '选定日期'} 暂无数据`" />
          </a-card>
        </a-col>
      </a-row>

      <a-divider />

      <a-row :gutter="[16, 16]">
        <a-col :span="24">
          <a-card title="面试邀约统计" :bordered="false">
            <a-row :gutter="[16, 16]" v-if="hasInvitedData">
              <a-col :span="12">
                <div class="invite-card">
                  <div class="invite-title">昨日面试邀约</div>
                  <div class="invite-value">{{ userInvitedDaily?.invited_1d || 0 }}</div>
                  <div class="invite-label">次</div>
                </div>
              </a-col>
              <a-col :span="12">
                <div class="invite-card">
                  <div class="invite-title">历史面试邀约</div>
                  <div class="invite-value">{{ userInvitedHistory?.invited_td || 0 }}</div>
                  <div class="invite-label">次</div>
                </div>
              </a-col>
            </a-row>
            <a-empty v-else description="暂无面试邀约数据" />
          </a-card>
        </a-col>
      </a-row>
    </a-card>

    <!-- 简历预览弹窗 -->
    <a-modal v-model:visible="resumePreviewVisible" title="简历预览" width="80%" :footer="null">
      <div class="resume-preview-container">
        <iframe :src="previewingResumeUrl" width="100%" height="600px"></iframe>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart, BarChart, LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
} from 'echarts/components'
import VChart from 'vue-echarts'
import dayjs from 'dayjs'
import {
  getExamAvgScoreUsingGet,
  getHrInterviewAvgScoreUsingGet,
  getFullProcessAvgScoreUsingGet,
  getUserBehaviorDailyUsingGet,
  getUserBehaviorMultiDayUsingGet,
  getUserInvitedDailyUsingGet,
  getUserInvitedHistoryUsingGet,
  getAiInterviewScore1DUsingGet,
  getResumeQualityScoreDailyUsingGet,
  getResumeQualityScoreHistoryUsingGet,
} from '../../../api/echartsController'
import { message } from 'ant-design-vue'

// 注册必要的组件
use([
  CanvasRenderer,
  PieChart,
  BarChart,
  LineChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
])

// 表格列定义
const resumeColumns = [
  {
    title: '简历名称',
    dataIndex: 'resumeName',
    key: 'resumeName',
    ellipsis: true,
  },
  {
    title: '公司',
    dataIndex: 'company',
    key: 'company',
  },
  {
    title: '职位',
    dataIndex: 'position',
    key: 'position',
  },
  {
    title: '得分',
    dataIndex: 'minTotalScore',
    key: 'minTotalScore',
    width: 200,
  },
  {
    title: '提交日期',
    dataIndex: 'countTIme',
    key: 'countTIme',
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
  },
]

// 简历预览状态
const resumePreviewVisible = ref(false)
const previewingResumeUrl = ref('')

// 基本数据状态
const examAvgScore = ref(0)
const hrAvgScore = ref(0)
const fullProcessAvgScore = ref(0)
const userBehaviorDaily = ref<any>(null)
const userBehaviorMulti = ref<any>(null)
const userInvitedDaily = ref<any>(null)
const userInvitedHistory = ref<any>(null)
const techInterviewInfo = ref<any>(null)
const resumeQualityDaily = ref<any[]>([])
const resumeQualityHistory = ref<any[]>([])
const selectedDate = ref<any>(dayjs().subtract(1, 'day')) // 默认选择昨天
const formattedSelectedDate = ref<string>('')
const selectedResumeDate = ref<any>(dayjs().subtract(1, 'day')) // 默认选择昨天
const formattedResumeSelectedDate = ref<string>('')

// 预览简历
const previewResume = (url: string) => {
  previewingResumeUrl.value = url
  resumePreviewVisible.value = true
}

// 下载简历
const downloadResume = (url: string) => {
  if (!url) {
    message.error('简历链接不存在')
    return
  }

  const link = document.createElement('a')
  link.href = url
  link.target = '_blank'
  link.download = '简历.pdf' // 可以根据需要修改下载文件名
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 获取分数颜色
const getScoreColor = (score: number) => {
  if (score >= 90) return '#52c41a'
  if (score >= 80) return '#1890ff'
  if (score >= 70) return '#faad14'
  return '#f5222d'
}

// 检查是否有简历质量日常数据
const hasResumeQualityDailyData = computed(() => {
  return resumeQualityDaily.value && resumeQualityDaily.value.length > 0
})

// 检查是否有简历质量历史数据
const hasResumeQualityHistoryData = computed(() => {
  return resumeQualityHistory.value && resumeQualityHistory.value.length > 0
})

// 检查是否有技术面试数据
const hasTechInterviewData = computed(() => {
  return techInterviewInfo.value !== null && techInterviewInfo.value !== undefined
})

// 检查是否有每日行为数据
const hasDailyBehaviorData = computed(() => {
  return userBehaviorDaily.value !== null && userBehaviorDaily.value !== undefined
})

// 检查是否有多日行为数据
const hasMultiBehaviorData = computed(() => {
  return userBehaviorMulti.value !== null && userBehaviorMulti.value !== undefined
})

// 检查是否有邀约数据
const hasInvitedData = computed(() => {
  return (
    (userInvitedDaily.value !== null && userInvitedDaily.value !== undefined) ||
    (userInvitedHistory.value !== null && userInvitedHistory.value !== undefined)
  )
})

// 禁用未来日期
const disabledDate = (current: any) => {
  return current && current > dayjs().endOf('day')
}

// 格式化时长
const formatDuration = (seconds: number) => {
  const minutes = Math.floor(seconds / 60)
  return minutes
}

// 每日行为图表配置
const dailyBehaviorOption = computed(() => {
  if (!userBehaviorDaily.value) return {}

  return {
    tooltip: {
      trigger: 'item',
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'center',
    },
    series: [
      {
        name: '面试行为',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2,
        },
        label: {
          show: false,
          position: 'center',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold',
          },
        },
        labelLine: {
          show: false,
        },
        data: [
          {
            value: userBehaviorDaily.value.interviewCount || 0,
            name: '面试次数',
            itemStyle: { color: '#1890ff' },
          },
          {
            value: userBehaviorDaily.value.hrInterviewCount || 0,
            name: 'HR面试',
            itemStyle: { color: '#52c41a' },
          },
          {
            value: userBehaviorDaily.value.examCount || 0,
            name: '笔试',
            itemStyle: { color: '#faad14' },
          },
          {
            value: userBehaviorDaily.value.resumeSubmitCount || 0,
            name: '简历上传',
            itemStyle: { color: '#f5222d' },
          },
        ],
      },
    ],
  }
})

// 多日行为图表配置
const multiBehaviorOption = computed(() => {
  if (!userBehaviorMulti.value) return {}

  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    legend: {
      data: ['7天数据', '30天数据'],
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: ['技术面试', 'HR面试', '笔试', '简历提交'],
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        name: '7天数据',
        type: 'bar',
        emphasis: {
          focus: 'series',
        },
        data: [
          userBehaviorMulti.value.interviewCount_7d || 0,
          userBehaviorMulti.value.hrInterviewCount_7d || 0,
          userBehaviorMulti.value.examCount_7d || 0,
          userBehaviorMulti.value.resumeSubmitCount_7d || 0,
        ],
        itemStyle: { color: '#1890ff' },
      },
      {
        name: '30天数据',
        type: 'bar',
        emphasis: {
          focus: 'series',
        },
        data: [
          userBehaviorMulti.value.interviewCount_30d || 0,
          userBehaviorMulti.value.hrInterviewCount_30d || 0,
          userBehaviorMulti.value.examCount_30d || 0,
          userBehaviorMulti.value.resumeSubmitCount_30d || 0,
        ],
        itemStyle: { color: '#52c41a' },
      },
    ],
  }
})

// 获取所有数据
const fetchAllData = async () => {
  try {
    // 获取笔试平均分
    const examResult = await getExamAvgScoreUsingGet()
    if (examResult.code === 0 && examResult.data) {
      examAvgScore.value = examResult.data.avgExamScore || 0
    }

    // 获取HR面试平均分
    const hrResult = await getHrInterviewAvgScoreUsingGet()
    if (hrResult.code === 0 && hrResult.data) {
      hrAvgScore.value = hrResult.data.avgHrScore || 0
    }

    // 获取全流程平均分
    const fullResult = await getFullProcessAvgScoreUsingGet()
    if (fullResult.code === 0 && fullResult.data) {
      fullProcessAvgScore.value = fullResult.data.avgExamScore || 0
    }

    // 获取技术面试统计
    const techResult = await getAiInterviewScore1DUsingGet()
    if (techResult.code === 0 && techResult.data) {
      techInterviewInfo.value = techResult.data
    }

    // 获取每日行为数据
    const dailyBehaviorResult = await getUserBehaviorDailyUsingGet()
    if (dailyBehaviorResult.code === 0 && dailyBehaviorResult.data) {
      userBehaviorDaily.value = {
        interviewCount: dailyBehaviorResult.data.interviewCount || 0,
        hrInterviewCount: dailyBehaviorResult.data.hrInterviewCount || 0,
        examCount: dailyBehaviorResult.data.examCount || 0,
        resumeSubmitCount: dailyBehaviorResult.data.resumeSubmitCount || 0,
      }
    } else {
      // 即使没有数据也初始化为空对象而不是null，防止渲染问题
      userBehaviorDaily.value = {
        interviewCount: 0,
        hrInterviewCount: 0,
        examCount: 0,
        resumeSubmitCount: 0,
      }
    }

    // 获取昨日多日行为数据
    const yesterdayDate = dayjs().subtract(1, 'day').format('YYYY-MM-DD')
    formattedSelectedDate.value = yesterdayDate
    const multiBehaviorResult = await getUserBehaviorMultiDayUsingGet({
      date: yesterdayDate,
    })
    if (multiBehaviorResult.code === 0 && multiBehaviorResult.data) {
      userBehaviorMulti.value = {
        interviewCount_7d: multiBehaviorResult.data.interviewCount_7d || 0,
        hrInterviewCount_7d: multiBehaviorResult.data.hrInterviewCount_7d || 0,
        examCount_7d: multiBehaviorResult.data.examCount_7d || 0,
        resumeSubmitCount_7d: multiBehaviorResult.data.resumeSubmitCount_7d || 0,
        interviewCount_30d: multiBehaviorResult.data.interviewCount_30d || 0,
        hrInterviewCount_30d: multiBehaviorResult.data.hrInterviewCount_30d || 0,
        examCount_30d: multiBehaviorResult.data.examCount_30d || 0,
        resumeSubmitCount_30d: multiBehaviorResult.data.resumeSubmitCount_30d || 0,
      }
    } else {
      userBehaviorMulti.value = null
    }

    // 获取面试邀约数据
    const invitedDailyResult = await getUserInvitedDailyUsingGet()
    if (invitedDailyResult.code === 0 && invitedDailyResult.data) {
      userInvitedDaily.value = invitedDailyResult.data
    }

    const invitedHistoryResult = await getUserInvitedHistoryUsingGet()
    if (invitedHistoryResult.code === 0 && invitedHistoryResult.data) {
      userInvitedHistory.value = invitedHistoryResult.data
    }

    // 获取简历质量日常数据
    const resumeQualityDailyResult = await getResumeQualityScoreDailyUsingGet()
    if (resumeQualityDailyResult.code === 0 && resumeQualityDailyResult.data) {
      resumeQualityDaily.value = resumeQualityDailyResult.data as any
    }

    // 获取简历质量历史数据
    formattedResumeSelectedDate.value = yesterdayDate
    const resumeQualityHistoryResult = await getResumeQualityScoreHistoryUsingGet({
      date: yesterdayDate,
    })
    if (resumeQualityHistoryResult.code === 0 && resumeQualityHistoryResult.data) {
      resumeQualityHistory.value = resumeQualityHistoryResult.data as any
    }
  } catch (error) {
    message.error('获取数据失败，请稍后重试')
    console.error('数据获取错误:', error)
  }
}

// 处理日期变更
const handleDateChange = async (date: any) => {
  if (!date) {
    userBehaviorMulti.value = null
    formattedSelectedDate.value = ''
    return
  }

  formattedSelectedDate.value = dayjs(date).format('YYYY-MM-DD')
  try {
    const result = await getUserBehaviorMultiDayUsingGet({
      date: formattedSelectedDate.value,
    })
    if (result.code === 0 && result.data) {
      userBehaviorMulti.value = {
        interviewCount_7d: result.data.interviewCount_7d || 0,
        hrInterviewCount_7d: result.data.hrInterviewCount_7d || 0,
        examCount_7d: result.data.examCount_7d || 0,
        resumeSubmitCount_7d: result.data.resumeSubmitCount_7d || 0,
        interviewCount_30d: result.data.interviewCount_30d || 0,
        hrInterviewCount_30d: result.data.hrInterviewCount_30d || 0,
        examCount_30d: result.data.examCount_30d || 0,
        resumeSubmitCount_30d: result.data.resumeSubmitCount_30d || 0,
      }
    } else {
      userBehaviorMulti.value = null
      message.warning('该日期暂无数据')
    }
  } catch (error) {
    userBehaviorMulti.value = null
    message.error('获取指定日期数据失败')
    console.error('日期变更错误:', error)
  }
}

// 处理简历质量日期变更
const handleResumeQualityDateChange = async (date: any) => {
  if (!date) {
    resumeQualityHistory.value = []
    formattedResumeSelectedDate.value = ''
    return
  }

  formattedResumeSelectedDate.value = dayjs(date).format('YYYY-MM-DD')
  try {
    const result = await getResumeQualityScoreHistoryUsingGet({
      date: formattedResumeSelectedDate.value,
    })
    if (result.code === 0 && result.data) {
      resumeQualityHistory.value = result.data as any
    } else {
      resumeQualityHistory.value = []
      message.warning('获取指定日期简历质量数据失败')
    }
  } catch (error) {
    resumeQualityHistory.value = []
    message.error('获取指定日期简历质量数据失败')
  }
}

onMounted(() => {
  // 获取基本数据
  fetchAllData()
})
</script>

<style scoped>
.interview-analysis-container {
  padding: 20px;
}

.score-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 150px;
}

.score-value {
  font-size: 48px;
  font-weight: bold;
  color: #1890ff;
}

.score-label {
  font-size: 16px;
  color: #8c8c8c;
}

.tech-info-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 120px;
  background-color: #f5f5f5;
  border-radius: 8px;
  padding: 16px;
}

.tech-info-title {
  font-size: 16px;
  color: #8c8c8c;
  margin-bottom: 8px;
}

.tech-info-value {
  font-size: 32px;
  font-weight: bold;
  color: #1890ff;
}

.tech-info-label {
  font-size: 14px;
  color: #8c8c8c;
}

.invite-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 120px;
  background-color: #f5f5f5;
  border-radius: 8px;
  padding: 16px;
}

.invite-title {
  font-size: 16px;
  color: #8c8c8c;
  margin-bottom: 8px;
}

.invite-value {
  font-size: 32px;
  font-weight: bold;
  color: #52c41a;
}

.invite-label {
  font-size: 14px;
  color: #8c8c8c;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.chart {
  width: 100%;
  height: 300px;
}

.date-selector {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.selected-date-text {
  margin-left: 16px;
  color: #8c8c8c;
}

.table-container {
  height: 300px;
  overflow: auto;
}

.resume-preview-container {
  width: 100%;
  height: 600px;
  overflow: auto;
}

.score-text {
  font-size: 16px;
  font-weight: bold;
}

:deep(.ant-table-thead > tr > th) {
  background-color: #f0f5ff;
  color: #1890ff;
  font-weight: bold;
}

:deep(.ant-card-head-title) {
  font-weight: bold;
  color: #1890ff;
}
</style>
